package com.zwh.autoconfigure.web;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zwh.common.exception.OperationException;
import com.zwh.common.persistence.ReturnObject;
import com.zwh.common.persistence.ReturnStatus;


/**
 * 全局异常处理类
 */
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class ExceptionControllerAdvice {
    private Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ReturnObject handleException(Throwable throwable) throws IOException {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logger.error("invoke fail: url={}", request.getRequestURI());

        ReturnObject res = new ReturnObject();
        res.setResult(ReturnStatus.returnFalse);
        if(throwable instanceof OperationException){
            OperationException operationException=(OperationException)throwable;
            res.setStatus(String.valueOf(operationException.getOperationStatus()));
            res.setMessage(operationException.getMessage());
            return res;
        }else if(throwable instanceof ValidationException){
            res.setStatus(ReturnStatus.STATUS_GLOBAL_WARN_MESSAGE);
            res.setMessage(throwable.getMessage());
            return res;
        }else if(throwable instanceof Exception){
            res.setStatus(ReturnStatus.STATUS_GLOBAL_WARN_MESSAGE);
            res.setMessage(throwable.getMessage());
            throwable.printStackTrace();
            return res;
        }else{
            return res;
        }
    }
}
